package top.fzqblog.kotlinapp.util

import io.reactivex.Observable
import org.jetbrains.anko.db.classParser
import org.jetbrains.anko.db.insert
import org.jetbrains.anko.db.select
import top.fzqblog.kotlinapp.app.KotlinApp
import top.fzqblog.kotlinapp.func.log
import top.fzqblog.kotlinapp.http.ApiRetrofit
import top.fzqblog.kotlinapp.http.LoginService
import top.fzqblog.kotlinapp.model.Info
import top.fzqblog.kotlinapp.model.LoginResult
import top.fzqblog.kotlinapp.tables.InfoTable

/**
 * Created by 抽离 on 2017/11/23 0023.
 */

fun getUnionId(): String? {
    val ankoDBHelper =  AnkoDBHelper.instance
    var unionId: String? = null;
    ankoDBHelper.use {
        val  infos = select(InfoTable.Table_Name)
                .whereArgs("(key = {key})", "key" to "unionId")
                .parseList(classParser<Info>())
        if(infos.isNotEmpty()){
            log("已经拥有unionId")
            unionId = infos[0].value
            log(unionId.toString())
        }
    }
    return unionId
}

fun addUnionId(unionId: String){
    val ankoDbHelper = AnkoDBHelper.instance
    ankoDbHelper.use {
        insert("info",
                "key" to "unionId",
                "value" to unionId)
    }
}


fun login(): Boolean{
    val apiRetrofit: ApiRetrofit = ApiRetrofit.getInstance(KotlinApp.instance)
    val loginService = apiRetrofit.create(LoginService::class.java)
    var flag = false
    loginService!!
            .getLoginResult()
            .subscribe({
              loginResult ->
                log(loginResult.toString())
                if (loginResult.msg == "toIndex"){
                   flag = true
                }
            },{
                throwable ->
                log(throwable.toString())
            })
    return flag
}
